package com.wzqj.agent.util;

import com.alibaba.fastjson.JSONObject;
import com.wzqj.agent.app.user.domain.AppToken;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

public class TokenUtil {

	public static final String LOGIN_THREEDES_KEY = "wzqjxltdwAoimbvy862wzqvy";// 生成token进行des加密的秘钥
	public static final String LOGIN_KEY = "wzqjpp@YPFEwe8eiouFHSAfjauief%&Fas";// 参数加密密钥
	public static final char TOKEN_PARTITION = 1;//token 各个字段分割符
	
	/**
	 * 将Token转换成返回的加密字符串
	 * 
	 * @param token
	 * @return
	 * @throws EncodingException
	 */
	public static String tokenToStr(AppToken token) throws UnsupportedEncodingException {
		StringBuffer sb = new StringBuffer();
		sb.append(token.getWid()).append(TOKEN_PARTITION)
			.append(token.getMk()).append(TOKEN_PARTITION)
            .append(token.getMt()).append(TOKEN_PARTITION)
            .append(token.getCreateTime());
        return URLEncoder.encode(ThreeDesUtil.threeDESencode(sb.toString(), LOGIN_THREEDES_KEY), "utf-8");
    }

	/**
	 * 将加密好的token转换成Loken对象
	 * 
	 * @param token
	 * @return
	 * @throws Exception
	 */
	public static AppToken strToToken(String token) throws Exception {

		String tokenStr = ThreeDesUtil.threeDESdecrypt(URLDecoder.decode(token,"utf-8"),LOGIN_THREEDES_KEY);
		String[] tokenArr = tokenStr.split(String.valueOf(TOKEN_PARTITION)) ;
		if ( 4 == tokenArr.length) {
			AppToken appToken = new AppToken();
            appToken.setWid(tokenArr[0]);
			appToken.setMk(tokenArr[1]) ;
            appToken.setMt(tokenArr[2]);
            appToken.setCreateTime(Long.parseLong(tokenArr[3]));
			return appToken;
		} else {
			return null ;
		}	
		
	}

	public static void main(String[] args) throws Exception {
		AppToken appToken = new AppToken();
		appToken.setMk("mk") ;
		appToken.setWid("13552754279") ;
        appToken.setCreateTime(System.currentTimeMillis());
        appToken.setMt("android");
		String result = tokenToStr(appToken) ;
		System.out.println(result);
		AppToken result2 = strToToken(result);
		JSONObject ob = (JSONObject) JSONObject.toJSON(result2);
		System.out.println(ob.toJSONString());

	}

}
